import { User, Address, ApiResponse } from '../types';
import { STORAGE_KEYS, getStorageData, setStorageData, getStorageItem, setStorageItem } from '../utils/storage';

// 生成UUID（简化版）
const generateUUID = (): string => {
  return 'addr_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// 邮箱格式验证
const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// ===== 通用权限验证函数 =====

/**
 * 获取当前登录用户
 */
export const getCurrentUser = (): Omit<User, 'password'> | null => {
  return getStorageItem<Omit<User, 'password'>>(STORAGE_KEYS.CURRENT_USER);
};

/**
 * 检查用户是否已登录
 */
export const checkAuth = (): { success: boolean; error?: ApiResponse<any> } => {
  const user = getCurrentUser();
  if (!user) {
    return {
      success: false,
      error: {
        code: 401,
        message: '请先登录',
        data: null
      }
    };
  }
  if (user.isBanned) {
    return {
      success: false,
      error: {
        code: 403,
        message: '账号已被封禁',
        data: null
      }
    };
  }
  return { success: true };
};

/**
 * 检查管理员权限
 */
export const checkAdmin = (): { success: boolean; error?: ApiResponse<any>; user?: Omit<User, 'password'> } => {
  const authResult = checkAuth();
  if (!authResult.success) {
    return authResult;
  }

  const user = getCurrentUser()!;
  if (!user.isAdmin) {
    return {
      success: false,
      error: {
        code: 403,
        message: '需要管理员权限',
        data: null
      }
    };
  }

  return { success: true, user };
};

// ===== Profile 相关功能 =====

export interface UpdateProfileRequest {
  username?: string;
  email?: string;
  phone?: string;
}

export interface ProfileResponse {
  user: Omit<User, 'password'>;
}

/**
 * 获取当前用户信息
 */
export const getProfile = async (): Promise<ApiResponse<ProfileResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const user = getCurrentUser()!;

    return {
      code: 200,
      message: '获取用户信息成功',
      data: {
        user
      }
    };

  } catch (error) {
    console.error('获取用户信息失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 更新用户信息
 */
export const updateProfile = async (params: UpdateProfileRequest): Promise<ApiResponse<ProfileResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { username, email, phone } = params;

    // 1. 参数验证
    if (username !== undefined) {
      if (!username || username.length < 2 || username.length > 20) {
        return {
          code: 400,
          message: '用户名长度必须在2-20个字符之间',
          data: null
        };
      }
    }

    if (email !== undefined) {
      if (!email || !validateEmail(email)) {
        return {
          code: 400,
          message: '邮箱格式不正确',
          data: null
        };
      }
    }

    if (phone !== undefined) {
      if (!phone) {
        return {
          code: 400,
          message: '手机号不能为空',
          data: null
        };
      }
    }

    // 2. 获取所有用户数据，检查唯一性
    const users = getStorageData<User>(STORAGE_KEYS.USERS);

    // 检查用户名唯一性（排除当前用户）
    if (username !== undefined && username !== currentUser.username) {
      const existingUser = users.find(u => u.username === username && u.id !== currentUser.id);
      if (existingUser) {
        return {
          code: 409,
          message: '用户名已存在',
          data: null
        };
      }
    }

    // 检查邮箱唯一性（排除当前用户）
    if (email !== undefined && email !== currentUser.email) {
      const existingUser = users.find(u => u.email === email && u.id !== currentUser.id);
      if (existingUser) {
        return {
          code: 409,
          message: '邮箱已被使用',
          data: null
        };
      }
    }

    // 检查手机号唯一性（排除当前用户）
    if (phone !== undefined && phone !== currentUser.phone) {
      const existingUser = users.find(u => u.phone === phone && u.id !== currentUser.id);
      if (existingUser) {
        return {
          code: 409,
          message: '手机号已被使用',
          data: null
        };
      }
    }

    // 3. 更新用户数据
    const updatedUsers = users.map(user => {
      if (user.id === currentUser.id) {
        return {
          ...user,
          username: username ?? user.username,
          email: email ?? user.email,
          phone: phone ?? user.phone,
          updatedAt: new Date().toISOString()
        };
      }
      return user;
    });

    // 4. 保存到localStorage
    setStorageData(STORAGE_KEYS.USERS, updatedUsers);

    // 5. 更新当前用户信息（不包含密码）
    const updatedUser: Omit<User, 'password'> = {
      ...currentUser,
      username: username ?? currentUser.username,
      email: email ?? currentUser.email,
      phone: phone ?? currentUser.phone,
      updatedAt: new Date().toISOString()
    };

    setStorageItem(STORAGE_KEYS.CURRENT_USER, updatedUser);

    return {
      code: 200,
      message: '用户信息更新成功',
      data: {
        user: updatedUser
      }
    };

  } catch (error) {
    console.error('更新用户信息失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 地址管理功能 =====

export interface AddAddressRequest {
  receiverName: string;
  phone: string;
  fullAddress: string;
}

export interface AddressResponse {
  address: Address;
}

export interface AddressListResponse {
  addresses: Address[];
}

/**
 * 获取用户地址列表
 */
export const getAddresses = async (): Promise<ApiResponse<AddressListResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 获取所有地址，筛选当前用户的地址
    const allAddresses = getStorageData<Address>(STORAGE_KEYS.ADDRESSES);
    const userAddresses = allAddresses.filter(address => address.userId === currentUser.id);

    return {
      code: 200,
      message: '获取地址列表成功',
      data: {
        addresses: userAddresses
      }
    };

  } catch (error) {
    console.error('获取地址列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 添加新地址
 */
export const addAddress = async (params: AddAddressRequest): Promise<ApiResponse<AddressResponse>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;
    const { receiverName, phone, fullAddress } = params;

    // 1. 参数验证
    if (!receiverName || !phone || !fullAddress) {
      return {
        code: 400,
        message: '收货人姓名、电话和地址都是必填的',
        data: null
      };
    }

    if (receiverName.length < 2 || receiverName.length > 10) {
      return {
        code: 400,
        message: '收货人姓名长度必须在2-10个字符之间',
        data: null
      };
    }

    if (fullAddress.length < 5 || fullAddress.length > 200) {
      return {
        code: 400,
        message: '地址长度必须在5-200个字符之间',
        data: null
      };
    }

    // 2. 创建新地址
    const newAddress: Address = {
      id: generateUUID(),
      userId: currentUser.id,
      receiverName: receiverName.trim(),
      phone: phone.trim(),
      fullAddress: fullAddress.trim()
    };

    // 3. 保存到localStorage
    const allAddresses = getStorageData<Address>(STORAGE_KEYS.ADDRESSES);
    const updatedAddresses = [...allAddresses, newAddress];
    setStorageData(STORAGE_KEYS.ADDRESSES, updatedAddresses);

    return {
      code: 200,
      message: '地址添加成功',
      data: {
        address: newAddress
      }
    };

  } catch (error) {
    console.error('添加地址失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 删除地址
 */
export const deleteAddress = async (addressId: string): Promise<ApiResponse<null>> => {
  try {
    // 检查登录状态
    const authResult = checkAuth();
    if (!authResult.success) {
      return authResult.error!;
    }

    const currentUser = getCurrentUser()!;

    // 1. 参数验证
    if (!addressId) {
      return {
        code: 400,
        message: '地址ID不能为空',
        data: null
      };
    }

    // 2. 获取所有地址
    const allAddresses = getStorageData<Address>(STORAGE_KEYS.ADDRESSES);

    // 3. 查找要删除的地址
    const addressToDelete = allAddresses.find(address => address.id === addressId);

    if (!addressToDelete) {
      return {
        code: 404,
        message: '地址不存在',
        data: null
      };
    }

    // 4. 检查地址是否属于当前用户
    if (addressToDelete.userId !== currentUser.id) {
      return {
        code: 403,
        message: '无权删除此地址',
        data: null
      };
    }

    // 5. 删除地址
    const updatedAddresses = allAddresses.filter(address => address.id !== addressId);
    setStorageData(STORAGE_KEYS.ADDRESSES, updatedAddresses);

    return {
      code: 200,
      message: '地址删除成功',
      data: null
    };

  } catch (error) {
    console.error('删除地址失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};


// ===== 管理员用户管理功能 =====

export interface UpdateUserPermissionRequest {
  userId: string;
  isAdmin?: boolean;
  isBanned?: boolean;
}

export interface UserPermissionResponse {
  user: Omit<User, 'password'>;
}

/**
 * 更新用户权限（管理员功能）
 */
export const updateUserPermission = async (params: UpdateUserPermissionRequest): Promise<ApiResponse<UserPermissionResponse>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    const currentAdmin = adminResult.user!;
    const { userId, isAdmin, isBanned } = params;

    // 1. 参数验证
    if (!userId) {
      return {
        code: 400,
        message: '用户ID不能为空',
        data: null
      };
    }

    if (isAdmin === undefined && isBanned === undefined) {
      return {
        code: 400,
        message: '至少需要指定一个要更新的权限字段',
        data: null
      };
    }

    // 2. 不能修改自己的权限
    if (userId === currentAdmin.id) {
      return {
        code: 403,
        message: '不能修改自己的权限',
        data: null
      };
    }

    // 3. 获取所有用户数据
    const users = getStorageData<User>(STORAGE_KEYS.USERS);

    // 4. 查找目标用户
    const targetUser = users.find(user => user.id === userId);
    if (!targetUser) {
      return {
        code: 404,
        message: '用户不存在',
        data: null
      };
    }

    // 5. 更新用户权限
    const updatedUsers = users.map(user => {
      if (user.id === userId) {
        return {
          ...user,
          isAdmin: isAdmin !== undefined ? isAdmin : user.isAdmin,
          isBanned: isBanned !== undefined ? isBanned : user.isBanned,
          updatedAt: new Date().toISOString()
        };
      }
      return user;
    });

    // 6. 保存到localStorage
    setStorageData(STORAGE_KEYS.USERS, updatedUsers);

    // 7. 如果目标用户当前正在登录，需要更新CURRENT_USER
    const currentUser = getCurrentUser();
    if (currentUser && currentUser.id === userId) {
      const updatedCurrentUser: Omit<User, 'password'> = {
        ...currentUser,
        isAdmin: isAdmin !== undefined ? isAdmin : currentUser.isAdmin,
        isBanned: isBanned !== undefined ? isBanned : currentUser.isBanned,
        updatedAt: new Date().toISOString()
      };
      setStorageItem(STORAGE_KEYS.CURRENT_USER, updatedCurrentUser);
    }

    // 8. 返回更新后的用户信息（不包含密码）
    const updatedUser = updatedUsers.find(user => user.id === userId)!;
    const userInfo: Omit<User, 'password'> = {
      id: updatedUser.id,
      username: updatedUser.username,
      email: updatedUser.email,
      phone: updatedUser.phone,
      avatar: updatedUser.avatar,
      isAdmin: updatedUser.isAdmin,
      isBanned: updatedUser.isBanned,
      createdAt: updatedUser.createdAt,
      updatedAt: updatedUser.updatedAt
    };

    return {
      code: 200,
      message: '用户权限更新成功',
      data: {
        user: userInfo
      }
    };

  } catch (error) {
    console.error('更新用户权限失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 获取所有用户列表（管理员功能）
 */
export interface UserListResponse {
  users: Omit<User, 'password'>[];
  total: number;
}

export const getAllUsers = async (): Promise<ApiResponse<UserListResponse>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    // 获取所有用户数据
    const users = getStorageData<User>(STORAGE_KEYS.USERS);

    // 过滤掉密码字段
    const usersWithoutPassword: Omit<User, 'password'>[] = users.map(user => ({
      id: user.id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      avatar: user.avatar,
      isAdmin: user.isAdmin,
      isBanned: user.isBanned,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt
    }));

    return {
      code: 200,
      message: '获取用户列表成功',
      data: {
        users: usersWithoutPassword,
        total: usersWithoutPassword.length
      }
    };

  } catch (error) {
    console.error('获取用户列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};